package com.travel.server.manager.impl.command.project;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.travel.common.CommonConstant;
import com.travel.common.util.CollectionUtil;
import com.travel.common.util.CommonUtil;
import com.travel.common.util.DateUtil;
import com.travel.server.manager.dto.request.project.UpdateProjectBaseInfoRequest;
import com.travel.server.manager.dto.request.project.UpdateProjectBaseInfoRequest.SpecialItem;
import com.travel.server.manager.dto.response.project.UpdateProjectBaseInfoResponse;
import com.travel.server.manager.impl.command.AbstractCommand;
import com.travel.server.manager.impl.dal.ProjectDal;
import com.travel.server.manager.impl.dal.SpecialDal;
import com.travel.server.manager.impl.youzan.YouzanSal;
import com.travel.server.manager.model.ProjectInfo;
import com.travel.server.manager.model.ProjectSpecial;
import com.travel.server.manager.model.UserInfo;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemUpdateParams;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemcategoriesTagsGetResult;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemsCustomGetResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Author: LiZhenhui
 * @Date: 2018/10/31 11:43
 * @Desc:
 */
@Component
@Slf4j
public class UpdateProjectBaseInfoCommand extends AbstractCommand<UpdateProjectBaseInfoRequest, UpdateProjectBaseInfoResponse> {

    @Autowired
    private ProjectDal projectDal;

    @Autowired
    private SpecialDal specialDal;

    @Value("${image.file.path}")
    private String imageFilePath;

    @Override
    protected void checkInput(UpdateProjectBaseInfoRequest request) {
    }

    @Override
    public UpdateProjectBaseInfoResponse handle(UpdateProjectBaseInfoRequest request) {

        UserInfo userInfo = getUserInfo();
        Date now = new Date();

        boolean needUpdatePic = false;
        boolean needUpdateGroup = false;

        ProjectInfo projectInfo = projectDal.getProjectInfo(request.getId(), userInfo);

        projectInfo.setCountry(request.getCountry());
        projectInfo.setProjectType(request.getType());
        projectInfo.setProjectGroup(request.getProject());
        if(projectInfo.getProjectGroup() == null || !projectInfo.getProjectGroup().equals(request.getProject())){
            needUpdateGroup = true;
        }
        projectInfo.setEmails(request.getEmails());
        projectInfo.setLimitNumber(request.getLimitNumber());
        if(request.getLinePrice() != null) {
            projectInfo.setLinePrice(CommonUtil.yuanToFen(request.getLinePrice()).longValue());
        }
        if(request.getMemberPrice() != null){
            projectInfo.setMemberPrice(CommonUtil.yuanToFen(request.getMemberPrice()).longValue());
        }
        projectInfo.setMemberType(request.getMemberType());
        projectInfo.setName(request.getName());
        projectInfo.setNeedEnglish(request.getNeedEnglish());
        projectInfo.setNumber(request.getNumber());
        projectInfo.setOrderChargeId(request.getOrderChargeId());
        projectInfo.setOrderChargeName(request.getOrderChargeName());
        projectInfo.setProjectChargeId(request.getProjectChargeId());
        projectInfo.setProjectChargeName(request.getProjectChargeName());
        if(request.getPrice() != null) {
            projectInfo.setPrice(CommonUtil.yuanToFen(request.getPrice()).longValue());
        }
        projectInfo.setProjectExplains(request.getExplains());
        if(projectInfo.getProjectPicUrl() == null || !projectInfo.getProjectPicUrl().equals(request.getPriUrl())){
            if(StringUtils.isNotBlank(request.getPriUrl())) {
                needUpdatePic = true;
            }
        }
        projectInfo.setProjectPicUrl(request.getPriUrl());
        projectInfo.setQuestionId(request.getQuestionId());
        if(StringUtils.isNotBlank(request.getShelfTime())) {
            projectInfo.setShelfTime(DateUtil.strToDate(request.getShelfTime(), DateUtil.YYYY_MM_DD));
        }
        projectInfo.setShelfType(request.getShelfType());
        projectInfo.setStock(request.getStock());
        projectInfo.setTravelType(request.getTravelTypeId());
        projectInfo.setUpdateBy(userInfo.getName());
        projectInfo.setUpdateTime(now);

        YouzanItemUpdateParams param = null;
        if(projectInfo.getId() != null){
            param = makeYouzanParam(projectInfo, needUpdatePic, needUpdateGroup);
        }

        projectDal.insertOrUpdate(projectInfo);

        if(!CollectionUtil.isEmpty(request.getSpecialList())){
            updateSpecial(request.getSpecialList(), projectInfo.getId(), userInfo, param);
        }

        if(param != null) {
            YouzanSal.updateYouzanItem(param);
        }

        UpdateProjectBaseInfoResponse response = new UpdateProjectBaseInfoResponse();
        response.setId(projectInfo.getId());

        return response;
    }

    private YouzanItemUpdateParams makeYouzanParam(ProjectInfo projectInfo, boolean needUpdatePic, boolean needUpdateGroup){
        YouzanItemUpdateParams param = new YouzanItemUpdateParams();
        YouzanItemsCustomGetResult youzanItemsCustomGetResult = YouzanSal.queryItem(projectInfo.getNumber());
        if(youzanItemsCustomGetResult != null && youzanItemsCustomGetResult.getItems() != null && youzanItemsCustomGetResult.getItems().length > 0){
            Long itemId = youzanItemsCustomGetResult.getItems()[0].getItemId();
            param.setItemId(itemId);
            param.setItemNo(projectInfo.getNumber());
            param.setTitle(projectInfo.getName());
            param.setDesc(projectInfo.getProjectExplains());
            param.setPrice(projectInfo.getPrice());
            param.setQuantity(Long.valueOf(projectInfo.getStock() + CommonConstant.EMPTY_STR));
            param.setOriginPrice(CommonUtil.fenToYuan(projectInfo.getLinePrice()).toString());
            if(projectInfo.getShelfTime() != null) {
                param.setAutoListingTime(projectInfo.getShelfTime().getTime());
            }
            if(projectInfo.getLimitNumber() != null){
                param.setBuyQuota(Long.parseLong(projectInfo.getLimitNumber() + CommonConstant.EMPTY_STR));
            }

            if(needUpdatePic){
                String imageIds = CommonConstant.EMPTY_STR;
                String[] picUrls = StringUtils.split(projectInfo.getProjectPicUrl(), CommonConstant.COMMON_STR);
                for(String picUrl : picUrls){
                    picUrl = imageFilePath + picUrl;
                    Long imageId = YouzanSal.uploadImage(picUrl);
                    if(imageId != null) {
                        imageIds = imageIds + imageId + CommonConstant.COMMON_STR;
                    }
                }
                if(StringUtils.isNotBlank(imageIds)){
                    imageIds = imageIds.substring(0, imageIds.length() - 1);
                    param.setImageIds(imageIds);
                }
            }
            if(needUpdateGroup){
                YouzanItemcategoriesTagsGetResult youzanItemcategoriesTagsGetResult = YouzanSal.queryTags();
                String tagIds = CommonConstant.EMPTY_STR;
                if(youzanItemcategoriesTagsGetResult != null && youzanItemcategoriesTagsGetResult.getTags() != null && youzanItemcategoriesTagsGetResult.getTags().length > 0){
                    for(YouzanItemcategoriesTagsGetResult.ItemGroupOpenModel item : youzanItemcategoriesTagsGetResult.getTags()){
                        if(item.getName().equals(projectInfo.getProjectGroup())){
                            tagIds = tagIds + item.getId() + CommonConstant.COMMON_STR;break;
                        }
                    }
                }
                if(StringUtils.isNotBlank(tagIds)){
                    tagIds = tagIds.substring(0, tagIds.length() - 1);
                    param.setTagIds(tagIds);
                }
            }
            return param;
        }
        return null;
    }

    private void updateSpecial(List<SpecialItem> specialItemList, Integer projectId, UserInfo userInfo, YouzanItemUpdateParams param){
        Date now = new Date();
        JSONArray array = new JSONArray();
        for(SpecialItem specialItem : specialItemList){
            Integer id = specialItem.getSpecialId();
            ProjectSpecial projectSpecial = null;
            if(id != null){
                projectSpecial = specialDal.selectById(id);
            }
            if(specialItem.getIsDelete() != null && CommonConstant.YES.equals(specialItem.getIsDelete())){
                //删除规格
                projectSpecial.setState(CommonConstant.NO);
            }else{
                if(projectSpecial == null){
                    projectSpecial = new ProjectSpecial();
                    projectSpecial.setState(CommonConstant.YES);
                    projectSpecial.setCreateBy(userInfo.getName());
                    projectSpecial.setCreateTime(now);
                }
                projectSpecial.setAttention(specialItem.getAttention());
                projectSpecial.setDays(specialItem.getDays());
                if(specialItem.getPrice() != null) {
                    projectSpecial.setPrice(CommonUtil.yuanToFen(specialItem.getPrice()).longValue());
                }
                projectSpecial.setProjectId(projectId);
                projectSpecial.setSalesVolume(specialItem.getSalesVolume());
                projectSpecial.setApplyAmount(specialItem.getApplyAmount());
                projectSpecial.setStock(specialItem.getStock());
                if(StringUtils.isNotBlank(specialItem.getTravelDate())) {
                    projectSpecial.setTravelDate(DateUtil.strToDate(specialItem.getTravelDate(), DateUtil.YYYY_MM_DD));
                }
                if(param != null) {
                    JSONObject item = new JSONObject();
                    item.put("price", specialItem.getPrice());
                    item.put("quantity", specialItem.getStock());

                    item.put("item_no", param.getItemNo());
                    JSONArray skuArray = new JSONArray();
                    if(StringUtils.isNotBlank(specialItem.getTravelDate()) && StringUtils.isNotBlank(specialItem.getDays())) {
                        JSONObject travelItem = new JSONObject();
                        travelItem.put("k", "出行日期");
                        Date travelDate = projectSpecial.getTravelDate();
                        Integer day = CommonUtil.getDays(specialItem.getDays());
                        Date travelEndDate = DateUtil.getIndexDay(travelDate, Calendar.DAY_OF_MONTH, day);
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                        travelItem.put("v", sdf.format(travelDate) + "-" + sdf.format(travelEndDate));
                        skuArray.add(travelItem);
                    }
                    if(StringUtils.isNotBlank(specialItem.getDays())) {
                        JSONObject daysItem = new JSONObject();
                        daysItem.put("k", "项目天数");
                        daysItem.put("v", specialItem.getDays());

                        skuArray.add(daysItem);
                    }
                    array.add(skuArray);
                }
            }
            projectSpecial.setUpdateBy(userInfo.getName());
            projectSpecial.setUpdateTime(now);
            specialDal.insertOrUpdate(projectSpecial);
        }
        if(param != null) {
            param.setSkuStocks(array.toJSONString());
        }
    }
}
